import React from 'react';
import { useState, useEffect, useCallback } from 'react';
import { Card, Button, Space } from 'antd';
import _ from 'lodash';
import DataEdit from './DataEdit';
import { CloseCircleOutlined } from '@ant-design/icons';
import { format } from '@/utils/datetime';
const stringSigns = [
  { value: 'like', label: '包含' },
  { value: 'leftlike', label: '开头是' },
  { value: 'rightlike', label: '结尾是' },
  { value: '=', label: '等于' },
  { value: '<>', label: '不等于' },
  { value: 'notlike', label: '不包含' },
  { value: 'empty', label: '空值' },
];
const numberSigns = [
  { value: '=', label: '等于' },
  { value: '>', label: '大于' },
  { value: '>=', label: '大于等于' },
  { value: '<', label: '小于' },
  { value: '<=', label: '小于等于' },
  { value: '<>', label: '不等于' },
  { value: 'between', label: '两值之间' },
  { value: 'null', label: '空值' },
];
const selectSigns = [
  { value: 'in', label: '包含' },
  { value: 'notin', label: '不包含' },
  { value: 'null', label: '空值' },
];
const controlTypeSigns = {
  text: stringSigns,
  date: numberSigns,
  year: numberSigns,
  month: numberSigns,
  time: numberSigns,
  datetime: numberSigns,
  'range-month': numberSigns,
  'range-date': numberSigns,
  'range-datetime': numberSigns,
  'range-number': numberSigns,
  select: selectSigns,
  'tree-select': selectSigns,
  'cascader-select': selectSigns,
  'checkbox-group': selectSigns,
  'radio-group': selectSigns,
  search: selectSigns,
  number: numberSigns,
  textarea: stringSigns,
};
type PropField = {
  /** 表头对应的控件 */
  control: API.Control;
  /** 过滤值 */
  filters?: API.WhereCause;
  /** 单位，默认为1 */
  unit?: number;
  /** 是否可以选择组合关系，默认为true */
  canSelectOR?: boolean;
  /** 是否显示 */
  visible: boolean;
  /** 取消按钮触发的回调 */
  onCancel: () => void;
  /** 清除按钮触发的回调 */
  onClear: (name: string) => void;
  /** 确定按钮触发的回调 */
  onOk: (values: API.WhereCause) => Promise<void>;
};
const FilterItem: React.FC<PropField> = (props) => {
  const [filters, setFilters] = useState<API.WhereCause>(
    _.isEmpty(props.filters)
      ? {
          WhereItems: [{ FieldName: props.control.name, Operator: '', FieldValues: '' }],
          RelationSign: 'AND',
        }
      : props.filters!,
  );
  const [controls, setControls] = useState<API.Control[]>([]);
  const [initVals, setInitVals] = useState<object>({});
  const [changeVals, setChangeVals] = useState<object>({});
  const handleSignChange = useCallback(
    (i: number, value: string) => {
      const newFilters = { ...filters };
      newFilters.WhereItems[i].Operator = value;
      setFilters(newFilters);
    },
    [filters],
  );
  useEffect(() => {
    let fType = props.control.type;
    let signsData = controlTypeSigns[fType!];
    if (!signsData) {
      signsData = stringSigns;
    }
    const conts: API.Control[] = [];
    switch (fType) {
      case 'checkbox-group':
      case 'radio-group':
        fType = 'select';
        break;
      case 'tree-select':
      case 'cascader-select':
        fType = 'tree-select';
        break;
      case 'range-date':
      case 'range-datetime':
      case 'search':
        throw new Error(`初始化过滤出错，不支持的控件类型${fType}`);
      default:
        break;
    }
    const initValues: object = {};
    for (let i = 0; i < filters.WhereItems.length; i++) {
      const f = filters.WhereItems[i];
      const crName = 'cr_' + i;
      const cvName = 'cv_' + i;
      initValues[crName] = _.isEmpty(f.Operator) ? signsData[0].value : f.Operator;
      conts.push({
        name: crName,
        type: 'select',
        label: '关系符',
        grid: 10 / 24,
        options: signsData,
        onChange: async (val) => handleSignChange(i, val),
        rules: [{ required: true, message: '关系符不能为空' }],
      });
      if (f.Operator === 'between') {
        if (fType === 'date') {
          fType = 'range-date';
        } else if (fType === 'datetime') {
          fType = 'range-datetime';
        } else if (fType === 'month') {
          fType = 'range-month';
        } else {
          fType = 'range-number';
        }
      }
      initValues[cvName] = _.isEmpty(f.FieldValues) ? undefined : f.FieldValues;
      const fCont: API.Control = {
        name: cvName,
        type: fType,
        label: '过滤值',
        grid: 14 / 24,
        rules: [{ required: true, message: '过滤值不能为空' }],
      };
      if (fType === 'select' || fType === 'tree-select') {
        if (props.control.fetch) {
          fCont.fetch = props.control.fetch;
        }
        if (props.control.options) {
          fCont.options = props.control.options;
        }
        fCont.multiple = true;
      }
      conts.push(fCont);
    }
    const sn = 'sign';
    initValues[sn] = 'AND';
    if (props.canSelectOR && filters.WhereItems.length > 1) {
      conts.push({
        name: sn,
        type: 'radio-group',
        label: '组合关系',
        grid: 24 / 24,
        options: [
          { value: 'AND', label: '并且' },
          { value: 'OR', label: '或者' },
        ],
        layout: { labelSpan: 6, wrapperSpan: 16 },
        rules: [{ required: true, message: '组合关系不能为空' }],
      });
    }
    setControls(conts!);
    setInitVals(initValues);
  }, [filters, props.control, props.canSelectOR, handleSignChange]);
  const handleClearFilters = async () => {
    setFilters({
      WhereItems: [{ FieldName: props.control.name, Operator: '', FieldValues: '' }],
      RelationSign: 'AND',
    });
    setChangeVals({});
    props.onClear!(props.control.name);
    if (props.onCancel) {
      props.onCancel();
    }
  };
  const handleSaveFilters = async (values: object) => {
    const sn = 'sign';
    const wc: API.WhereCause = { WhereItems: [], RelationSign: values[sn] };
    for (let i = 1; i < controls.length; i = i + 2) {
      const c = controls[i];
      const idx = (i - 1) / 2;
      const crName = 'cr_' + idx;
      const cvName = 'cv_' + idx;
      const unit = props.unit === 0 ? 1 : props.unit;
      if (values[cvName] !== undefined) {
        if (c.dataType === 'number' || c.type === 'number') {
          values[cvName] = values[cvName] * unit!;
        } else if (c.type === 'date' || c.type === 'datetime') {
          values[cvName] = format(values[cvName], 'yyyy-MM-dd');
        }
        wc.WhereItems.push({
          FieldName: props.control.name,
          FieldValues: '' + values[cvName],
          Operator: values[crName],
        });
      }
    }
    if (props.onOk) {
      props.onOk(wc);
    }
    if (props.onCancel) {
      props.onCancel();
    }
  };
  const handleAddFilters = () => {
    const newFilters = { ...filters };
    newFilters.WhereItems.push({ FieldName: props.control.name, Operator: '', FieldValues: '' });
    setFilters(newFilters);
  };
  const handleDeleteFilters = () => {
    if (filters.WhereItems.length <= 1) {
      return;
    }
    const newFilters = { ...filters };
    newFilters.WhereItems.splice(filters.WhereItems.length - 1);
    setFilters(newFilters);
  };
  const handleHideFilter = () => {
    if (props.onCancel) {
      props.onCancel();
    }
  };
  if (_.isEmpty(controls) || !props.visible) {
    return <></>;
  }
  return (
    <Card
      key={props.control.name}
      title={
        <>
          {`${props.control.label}过滤`}
          <CloseCircleOutlined
            style={{ float: 'right', color: 'red' }}
            onClick={handleHideFilter}
          />
        </>
      }
      bodyStyle={{ width: 600 }}
    >
      <DataEdit
        showType="inner"
        layout="horizontal"
        controls={controls!}
        onSumit={handleSaveFilters}
        onValuesChange={(_cvals, vals) => setChangeVals(vals)}
        initVals={{ ...initVals, ...changeVals }}
        renderButtons={(p) => {
          const butts = [
            <Button key={1} onClick={handleAddFilters}>
              新增
            </Button>,
            <Button key={0} onClick={handleClearFilters}>
              清除
            </Button>,
          ];
          if (filters.WhereItems.length > 1) {
            butts.push(
              <Button key={2} onClick={handleDeleteFilters}>
                减少
              </Button>,
            );
          }
          butts.push(
            <Button key={3} onClick={() => p.form?.submit?.()}>
              确定
            </Button>,
          );
          butts.push(
            <Button key={4} onClick={handleHideFilter}>
              取消
            </Button>,
          );
          return <Space style={{ float: 'right' }}>{butts}</Space>;
        }}
      />
    </Card>
  );
};
export default FilterItem;
FilterItem.defaultProps = {
  control: undefined,
  filters: undefined,
  onOk: undefined,
  unit: 1,
  canSelectOR: true,
};
